<script setup lang="ts">
import { computed, shallowRef, watch } from 'vue';
import type { DataNode } from 'ant-design-vue/es/tree';
import { $t } from '@/locales';
import { fetchGetAllButtons, fetchGetRoleButtons, fetchUpdateRoleButtons } from '@/service/api/system-manage';
import { useAuth } from '@/hooks/business/auth';

defineOptions({
  name: 'ButtonAuthModal'
});

interface Props {
  /** the roleId */
  roleId: number;
}

const props = defineProps<Props>();

const visible = defineModel<boolean>('open', {
  default: false
});

const { clearButtonPermissionCache } = useAuth();

function closeModal() {
  visible.value = false;
}

const title = computed(() => $t('common.edit') + $t('page.manage.role.buttonAuth'));

const tree = shallowRef<DataNode[]>([]);

async function getAllButtons() {
  try {
    console.log('开始获取所有按钮权限...');
    const { error, data } = await fetchGetAllButtons();

    if (!error && data && Array.isArray(data)) {
      // 将按钮权限数据转换为树形结构
      const buttonNodes: DataNode[] = data.map(button => ({
        key: button.code,
        title: `${button.name} (${button.code})`,
        code: button.code,
        desc: button.desc,
        category: button.category
      }));

      tree.value = buttonNodes;
    } else {
      console.warn('获取按钮权限失败，使用默认数据');
      // 使用默认数据作为备选
      tree.value = [
        { key: 'B_CODE1', title: '超级管理员可见按钮 (B_CODE1)', code: 'B_CODE1' },
        { key: 'B_CODE2', title: '管理员可见按钮 (B_CODE2)', code: 'B_CODE2' },
        { key: 'B_CODE3', title: '管理员或用户可见按钮 (B_CODE3)', code: 'B_CODE3' },
        { key: 'USER_ADD', title: '新增用户 (USER_ADD)', code: 'USER_ADD' },
        { key: 'USER_EDIT', title: '编辑用户 (USER_EDIT)', code: 'USER_EDIT' },
        { key: 'USER_DELETE', title: '删除用户 (USER_DELETE)', code: 'USER_DELETE' },
        { key: 'ROLE_ADD', title: '新增角色 (ROLE_ADD)', code: 'ROLE_ADD' },
        { key: 'ROLE_EDIT', title: '编辑角色 (ROLE_EDIT)', code: 'ROLE_EDIT' },
        { key: 'ROLE_DELETE', title: '删除角色 (ROLE_DELETE)', code: 'ROLE_DELETE' },
        { key: 'MENU_ADD', title: '新增菜单 (MENU_ADD)', code: 'MENU_ADD' },
        { key: 'MENU_EDIT', title: '编辑菜单 (MENU_EDIT)', code: 'MENU_EDIT' },
        { key: 'MENU_DELETE', title: '删除菜单 (MENU_DELETE)', code: 'MENU_DELETE' },
        { key: 'CURVE_ADD', title: '新增曲线点 (CURVE_ADD)', code: 'CURVE_ADD' },
        { key: 'CURVE_EDIT', title: '编辑曲线点 (CURVE_EDIT)', code: 'CURVE_EDIT' },
        { key: 'CURVE_DELETE', title: '删除曲线点 (CURVE_DELETE)', code: 'CURVE_DELETE' },
        { key: 'CURVE_VIEW', title: '查看曲线点 (CURVE_VIEW)', code: 'CURVE_VIEW' }
      ];
    }
  } catch (error) {
    console.error('获取按钮权限异常:', error);
    // 使用默认数据
    tree.value = [
      { key: 'B_CODE1', title: '超级管理员可见按钮 (B_CODE1)', code: 'B_CODE1' },
      { key: 'B_CODE2', title: '管理员可见按钮 (B_CODE2)', code: 'B_CODE2' },
      { key: 'B_CODE3', title: '管理员或用户可见按钮 (B_CODE3)', code: 'B_CODE3' },
      { key: 'CURVE_ADD', title: '新增曲线点 (CURVE_ADD)', code: 'CURVE_ADD' },
      { key: 'CURVE_EDIT', title: '编辑曲线点 (CURVE_EDIT)', code: 'CURVE_EDIT' },
      { key: 'CURVE_DELETE', title: '删除曲线点 (CURVE_DELETE)', code: 'CURVE_DELETE' },
      { key: 'CURVE_VIEW', title: '查看曲线点 (CURVE_VIEW)', code: 'CURVE_VIEW' }
    ];
  }
}

const checks = shallowRef<string[]>([]);

async function getChecks() {
  try {
    const { error, data } = await fetchGetRoleButtons(props.roleId);

    if (!error && data && Array.isArray(data)) {
      checks.value = data;
    } else {
      checks.value = [];
      console.warn('获取角色按钮权限失败，使用空权限');
    }
  } catch (error) {
    console.error('获取角色按钮权限异常:', error);
    checks.value = [];
  }
}

async function handleSubmit() {
  try {
    console.log('开始提交按钮权限...');
    console.log('角色ID:', props.roleId);
    console.log('选中的按钮权限:', checks.value);

    const { error } = await fetchUpdateRoleButtons(props.roleId, checks.value);

    if (!error) {
      console.log('按钮权限更新成功');
      window.$message?.success?.($t('common.modifySuccess'));
      closeModal();
      clearButtonPermissionCache();
    } else {
      console.error('按钮权限更新失败:', error);
      window.$message?.error?.('操作失败');
    }
  } catch (error) {
    console.error('更新角色按钮权限失败:', error);
    window.$message?.error?.('操作失败');
  }
}

async function init() {
  await getAllButtons();
  await getChecks();
}

watch(visible, val => {
  if (val) {
    init();
  }
});
</script>

<template>
  <AModal v-model:open="visible" :title="title" class="w-480px">
    <div class="mb-16px">
      <div class="mb-8px text-sm text-gray-600">选择该角色拥有的按钮权限：</div>
      <ATree
        v-model:checked-keys="checks"
        :tree-data="tree"
        checkable
        :height="280"
        class="h-280px"
        :field-names="{ key: 'key', title: 'title' }"
      />
    </div>
    <template #footer>
      <AButton size="small" class="mt-16px" @click="closeModal">
        {{ $t('common.cancel') }}
      </AButton>
      <AButton type="primary" size="small" class="mt-16px" @click="handleSubmit">
        {{ $t('common.confirm') }}
      </AButton>
    </template>
  </AModal>
</template>

<style scoped></style>
